<template>
  <div class="warehouse-container">
    <!-- 查询条件卡片（移到顶部） -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon><Search /></el-icon>
          <span>查询条件</span>
        </div>
      </template>
      <el-form :inline="true" :model="formInline" class="search-form">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="出入库单号">
              <el-input
                v-model="formInline.Warehouse_Code"
                placeholder="请输入出库单号/入库单号"
                clearable
                class="custom-input"
              >
                <template #prefix>
                  <el-icon><Document /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库名称">
              <el-select
                v-model="formInline.Warehouse_ID"
                placeholder="请选择"
                clearable
                class="custom-select"
              >
                <el-option
                  v-for="item in deplarment"
                  :label="item.warehouse_Name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务类型">
              <el-select
                v-model="formInline.WarehouseType"
                placeholder="请选择"
                clearable
                class="custom-select"
              >
                <el-option label="入库" :value="1" />
                <el-option label="出库" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 8px">
          <el-col :span="8">
            <el-form-item label="出入库类型">
              <el-select
                v-model="formInline.Warehousing_Type"
                placeholder="请选择"
                clearable
                class="custom-select"
              >
                <el-option label="采购收货入库" value="采购收货入库" />
                <el-option label="销售退货入库" value="销售退货入库" />
                <el-option label="生产产品入库" value="生产产品入库" />
                <el-option label="领用退还入库" value="领用退还入库" />
                <el-option label="销售出库" value="销售出库" />
                <el-option label="生产领用出库" value="生产领用出库" />
                <el-option label="领用退还出库" value="领用退还出库" />
                <el-option label="调拨入库" value="调拨入库" />
                <el-option label="调拨出库" value="调拨出库" />
                <el-option label="移动入库" value="移动入库" />
                <el-option label="移动出库" value="移动出库" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="出入库日期">
              <el-date-picker
                v-model="formInline.ReviewTime"
                type="date"
                placeholder="请选择"
                style="width: 100%"
                class="custom-date-picker"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单日期">
              <el-date-picker
                v-model="formInline.CreateTime"
                type="date"
                placeholder="请选择"
                style="width: 100%"
                class="custom-date-picker"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 8px">
          <el-col :span="24" style="text-align: right; white-space: nowrap">
            <el-form-item>
              <el-button type="primary" @click="getdata()" class="search-btn">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetForm" class="reset-btn">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 主要内容区域（去除顶部标题卡片，调整间隔） -->
    <div class="main-content" style="margin-top: 0">
      <!-- 统计卡片 -->
      <div class="stats-section">
        <el-card class="stats-card count-card" shadow="hover">
          <div class="stats-row">
            <div class="stats-item">
              <div class="stats-number inbound-count">
                {{ totalInboundCount }}
              </div>
              <div class="stats-label">入库数量</div>
            </div>
            <div class="stats-divider"></div>
            <div class="stats-item">
              <div class="stats-number outbound-count">
                {{ totalOutboundCount }}
              </div>
              <div class="stats-label">出库数量</div>
            </div>
          </div>
        </el-card>
        <el-card class="stats-card amount-card" shadow="hover">
          <div class="stats-row">
            <div class="stats-item">
              <div class="stats-number inbound-amount">
                ¥{{ totalInboundAmount }}
              </div>
              <div class="stats-label">入库金额</div>
            </div>
            <div class="stats-divider"></div>
            <div class="stats-item">
              <div class="stats-number outbound-amount">
                ¥{{ totalOutboundAmount }}
              </div>
              <div class="stats-label">出库金额</div>
            </div>
          </div>
        </el-card>
      </div>
      <!-- 数据表格卡片 -->
      <el-card class="table-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <el-icon><List /></el-icon>
            <span>出入库流水</span>
            <div class="header-actions">
              <el-button
                type="success"
                @click="handleExport()"
                class="export-btn"
              >
                <el-icon><Download /></el-icon>
                导出
              </el-button>
              <el-button type="primary" @click="getdata()" class="refresh-btn">
                <el-icon><Refresh /></el-icon>
                刷新
              </el-button>
            </div>
          </div>
        </template>
        <el-table
          :data="tableData"
          style="width: 100%"
          class="custom-table"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="warehouse_Code" label="序号" width="80">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="warehouse_Code"
            label="出入库单号"
            width="150"
          />
          <el-table-column prop="reviewTime" label="出入库日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.reviewTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="warehouseType" label="业务类型" width="100">
            <template #default="scope">
              <el-tag
                :type="scope.row.warehouseType == 1 ? 'success' : 'danger'"
                size="small"
              >
                {{ scope.row.warehouseType == 1 ? "入库" : "出库" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="warehousing_Type"
            label="出入库类型"
            width="120"
          />
          <el-table-column prop="warehouse_Name" label="仓库名称" width="100" />
          <el-table-column
            prop="warehouse_InOrOutCount"
            label="入库数量"
            width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.warehouseType == 1" class="inbound-count">
                {{ scope.row.warehouse_InOrOutCount }}
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="warehouse_InOrOutCount"
            label="出库数量"
            width="100"
          >
            <template #default="scope">
              <span v-if="scope.row.warehouseType == 2" class="outbound-count">
                {{ scope.row.warehouse_InOrOutCount }}
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="total_Price" label="入库金额" width="120">
            <template #default="scope">
              <span v-if="scope.row.warehouseType == 1" class="inbound-amount">
                ¥{{ scope.row.total_Price }}
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="total_Price" label="出库金额" width="120">
            <template #default="scope">
              <span v-if="scope.row.warehouseType == 2" class="outbound-amount">
                ¥{{ scope.row.total_Price }}
              </span>
              <span v-else>--</span>
            </template>
          </el-table-column>
          <el-table-column prop="reviewer" label="经办人" width="100" />
          <el-table-column prop="createUse" label="制单人" width="100">
            <template #default="scope">
              <span v-if="scope.row.createUse == '10032'">吴维昊</span>
              <span v-if="scope.row.createUse == '10036'">王雨龙</span>
              <span v-if="scope.row.createUse == '10037'">张可欣</span>
              <span v-if="scope.row.createUse == '10038'">赵姝雅</span>
              <span v-if="scope.row.createUse == '10039'">段栋兴</span>
            </template>
          </el-table-column>
          <el-table-column prop="department" label="所在部门" width="100">
            <template #default> 仓储部 </template>
          </el-table-column>
          <el-table-column prop="createTime" label="制单" width="120">
            <template #default> 2025-08-02 </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="page.PageIndex"
            v-model:page-size="page.PageSize"
            :page-sizes="[15, 20, 25, 30]"
            layout="total, sizes, prev, pager, next, jumper"
            prev-text="上一页"
            next-text="下一页"
            :total="page.totalCount"
            class="custom-pagination"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { reactive, onMounted, ref, watch, computed } from "vue";
import { BasicsRed, StorageRed } from "@/http/axiosHelper";
import { ElMessage, ElMessageBox } from "element-plus";
import { BasicsWrite } from "@/http/axiosHelper";
import { useRouter } from "vue-router";
// import { StorageRed } from "@/http/axiosHelper";
import {
  Box,
  Search,
  Document,
  Refresh,
  ArrowDown,
  ArrowUp,
  Money,
  List,
  Download,
} from "@element-plus/icons-vue";

const router = useRouter();
const dialogVisible = ref(false);

function formatDate(dateStr: string) {
  if (!dateStr) return "";
  const date = new Date(dateStr);
  if (isNaN(date.getTime())) return dateStr;
  const y = date.getFullYear();
  const m = String(date.getMonth() + 1).padStart(2, "0");
  const d = String(date.getDate()).padStart(2, "0");
  return `${y}-${m}-${d}`;
}

// 重置表单
const resetForm = () => {
  Object.assign(formInline, {
    Warehouse_Code: "",
    Warehousing_Type: "",
    Warehouse_ID: null,
    Reviewer: "",
    Product_Name: "",
    Category_ID: null,
    Unit_ID: null,
    ReviewTime:null,
    CreateTime:null,
    CreateUse: null,
    WarehouseType: null,
  });
  getdata();
  ElMessage.success("查询条件已重置");
};

const formInline = reactive({
  WarehouseType: "",
  Warehouse_Code: "",
  Warehousing_Type: "",
  Warehouse_ID: null,
  Reviewer: "",
  Product_Name: "",
  Category_ID: null,
  Unit_ID: null,
  ReviewTime:null,
  CreateTime:null,
  CreateUse: null,
});

const page = reactive({
  PageIndex: 1,
  PageSize: 15,
  totalCount: 0,
});

// 导出函数（假设已配置 Axios 拦截器自动添加 Token）
async function handleExport() {
  try {
    // 1. 调用后端导出接口（GET 请求，参数通过 params 传递）
    const response = await StorageRed({
      url: "/api/WorkOrder/StorageGetWarehouse_InExport", // 后端接口地址
      method: "GET",
      params: {
        PageIndex: page.PageIndex,
        PageSize: page.PageSize,
        Category_ID: formInline.Category_ID,
        CreateTime: formInline.CreateTime,
        CreateUse: formInline.CreateUse,
        Product_Name: formInline.Product_Name,
        ReviewTime: formInline.ReviewTime,
        Reviewer: formInline.Reviewer,
        Unit_ID: formInline.Unit_ID,
        Warehouse_Code: formInline.Warehouse_Code,
        Warehouse_ID: formInline.Warehouse_ID,
        Warehousing_Type: formInline.Warehousing_Type,
        WarehouseType: formInline.WarehouseType,
      }, // 对应后端 [FromQuery] 的 command 参数
      responseType: "blob", // 关键：指定响应类型为二进制流（Excel 文件）
    });

    // 2. 从响应头获取文件名（后端通过 File 方法设置的 fileName）
    const fileName = getFileNameFromHeaders(response.headers);

    // 3. 生成下载链接并触发下载
    const blob = new Blob([response.data], {
      type:
        response.headers["content-type"] ||
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = fileName; // 文件名从响应头获取或自定义
    document.body.appendChild(a);
    a.click();

    // 4. 清理资源
    window.URL.revokeObjectURL(url);
    document.body.removeChild(a);

    ElMessage.success("导出成功");
  } catch (error: any) {
    // 处理错误（如后端返回 401/400 等）
    console.error("导出失败：", error.response?.data || error.message);
    ElMessage.error("导出失败，请检查参数或重新登录");
  }
}

// 辅助函数：从响应头提取文件名（后端通过 File 方法设置）
function getFileNameFromHeaders(headers: any) {
  const contentDisposition =
    headers["content-disposition"] || headers["Content-Disposition"];
  if (!contentDisposition) return "入库流水.xlsx"; // 默认文件名

  // 解码文件名（处理中文编码问题）
  const match = contentDisposition.match(/filename\*?=([^;]+)/);
  if (match) {
    return decodeURIComponent(match[1].replace(/["']/g, ""));
  }
  return "入库流水.xlsx";
}

watch(page, () => {
  getdata();
});

onMounted(() => {
  delparmentdata();
  getdata();
});

const deplarment = ref();
//仓库下拉框
const delparmentdata = () => {
  StorageRed.get("/api/Warehouse_InOrOut/GetWarehouseModel").then((res) => {
    deplarment.value = res.data.data;
  });
};

const tableData = ref([]);

const getdata = () => {
  StorageRed.get("/api/WorkOrder/GetWarehouse_InFlowingWater", {
    params: {
      PageIndex: page.PageIndex,
      PageSize: page.PageSize,
      Category_ID: formInline.Category_ID,
      CreateTime: formInline.CreateTime,
      CreateUse: formInline.CreateUse,
      Product_Name: formInline.Product_Name,
      ReviewTime: formInline.ReviewTime,
      Reviewer: formInline.Reviewer,
      Unit_ID: formInline.Unit_ID,
      Warehouse_Code: formInline.Warehouse_Code,
      Warehouse_ID: formInline.Warehouse_ID,
      Warehousing_Type: formInline.Warehousing_Type,
      WarehouseType: formInline.WarehouseType,
    },
  }).then((res) => {
    tableData.value = res.data.data;
    page.totalCount = res.data.totalCount;
  });
};

// 定义数据类型接口
interface WarehouseItem {
  warehouseType: number;
  warehouse_InOrOutCount: number;
  total_Price: number;
  warehouse_Code: string;
  reviewTime: string;
  warehousing_Type: string;
  warehouse_Name: string;
  reviewer: string;
  createUse: string;
  [key: string]: any; // 允许其他属性
}

// 计算入库数量和入库金额总和
const totalInboundCount = computed(() => {
  return (tableData.value as WarehouseItem[])
    .filter((item) => item.warehouseType == 1) // 只统计入库数据
    .reduce((sum, item) => sum + (item.warehouse_InOrOutCount || 0), 0);
});

const totalInboundAmount = computed(() => {
  return (tableData.value as WarehouseItem[])
    .filter((item) => item.warehouseType == 1) // 只统计入库数据
    .reduce((sum, item) => sum + (item.total_Price || 0), 0)
    .toFixed(2);
});

// 计算出库数量和出库金额总和
const totalOutboundCount = computed(() => {
  return (tableData.value as WarehouseItem[])
    .filter((item) => item.warehouseType == 2) // 只统计出库数据
    .reduce((sum, item) => sum + (item.warehouse_InOrOutCount || 0), 0);
});

const totalOutboundAmount = computed(() => {
  return (tableData.value as WarehouseItem[])
    .filter((item) => item.warehouseType == 2) // 只统计出库数据
    .reduce((sum, item) => sum + (item.total_Price || 0), 0)
    .toFixed(2);
});
</script>

<style scoped>
.warehouse-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

/* 查询卡片间距优化 */
.search-card {
  margin-bottom: 24px;
}

.main-content {
  display: flex;
  flex-direction: column;
  gap: 24px;
  margin-top: 0;
}

/* 页面头部 */
.page-header {
  background: white;
  border-radius: 8px;
  padding: 20px 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
}
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}
.header-icon {
  font-size: 32px;
  color: #409eff;
  background: none;
}
.page-title {
  font-size: 24px;
  font-weight: 700;
  color: #222;
  background: none;
}
.page-subtitle {
  color: #6c757d;
  font-size: 16px;
  font-weight: 500;
  padding: 8px 16px;
  background: rgba(108, 117, 125, 0.1);
  border-radius: 8px;
  border: 1px solid rgba(108, 117, 125, 0.2);
}

/* 卡片统一样式 */
.search-card,
.stats-card,
.table-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
  margin-bottom: 20px;
}

/* 统计卡片 */
.stats-section {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}
.stats-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 24px;
}
.stats-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}
.stats-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}
.stats-divider {
  width: 1px;
  height: 40px;
  background: #e0e0e0;
  margin: 0 20px;
}
.stats-number {
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 8px;
}
.stats-label {
  color: #666;
  font-size: 14px;
  font-weight: 500;
}
.inbound-count {
  color: #67c23a;
}
.outbound-count {
  color: #f56c6c;
}
.inbound-amount {
  color: #409eff;
}
.outbound-amount {
  color: #e6a23c;
}

/* 表单控件 */
.custom-input,
.custom-select,
.custom-date-picker {
  border-radius: 8px;
  width: 200px;
}
.search-btn,
.reset-btn,
.export-btn,
.refresh-btn {
  border-radius: 8px;
  padding: 8px 16px;
  font-weight: 500;
  margin-right: 8px;
}
.search-btn,
.refresh-btn {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  border: none;
  color: #fff;
}
.search-btn:hover,
.refresh-btn:hover {
  background: linear-gradient(135deg, #337ecc 0%, #2d6aad 100%);
}
.reset-btn {
  background: #f8f9fa;
  border: 2px solid #dee2e6;
  color: #6c757d;
}
.reset-btn:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

/* 表格样式 */
.table-card .el-table th {
  background-color: #f8f9fa;
  color: #333;
  font-weight: 600;
}
.table-card .el-table {
  border-radius: 8px;
  overflow: hidden;
}

/* 分页样式 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}
.custom-pagination {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  padding: 8px 16px;
}

/* 响应式 */
@media (max-width: 1200px) {
  .warehouse-container {
    padding: 16px;
  }
  .stats-section {
    grid-template-columns: repeat(2, 1fr);
  }
  .page-header {
    padding: 20px 24px;
  }
  .page-title {
    font-size: 20px;
  }
}
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }
  .stats-section {
    grid-template-columns: 1fr;
  }
  .header-actions {
    flex-direction: column;
    gap: 8px;
  }
  .export-btn,
  .refresh-btn {
    width: 100%;
  }
}
</style>
